#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include <errno.h>
#include <stdlib.h>

#include <sys/fcntl.h>
#include <sys/types.h>

#include "cfs.h"


int main(int argc, const char **argv) {
	char *fname = (char *) argv[1];
	char *file = (char *) argv[2];
	int fd;

	if (!fname) {
		printf("usage: cat device file-name. \n");
		return 1;
	}

	fd = open(fname, O_RDWR);
	if (fd < 0) {
		printf("failed when trying to open %s: %s\n", fname, strerror(errno));
		return 1;
	}

	cfs_init(fd);

	struct inode *ino = cfs_search(rootdir, file);

	if (!ino) {
		printf("fatal: %s not found. \n", file);
		close(fd);

		return 1;
	}

	char *buf = malloc(fsize(ino));
	if (!buf) {
		printf("failed when allocate space: %d bytes need. \n", fsize(ino));

		close(fd);
		return 1;
	}

	cfs_read(ino, buf, fsize(ino));

	int i;

	for (i = 0; i < fsize(ino); i++) 
		putc(buf[i], stdout);

	close(fd);

	return 0;
}
